<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\RechargeModel;
use App\Services\PayServices;
use Illuminate\Support\Facades\DB;

class RechargeDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = RechargeModel::query();
        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });
        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });
        $query->when(checkIsHasField($params,'recharge_id'),function ($query)use ($params){
            $query->where('recharge_id',$params['recharge_id']);
        });
        $query->when(checkIsHasField($params,'pay_type'),function ($query)use ($params){
            $query->where('pay_type',$params['pay_type']);
        });

        $query->when(checkIsHasField($params,'order_code'),function ($query)use ($params){
            $query->where('order_code',$params['order_code']);
        });

        $query->when(checkIsHasField($params,'start_time'),function ($query)use ($params){
            $query->where('created_at','>=',strtotime($params['start_time']));
        });

        $query->when(checkIsHasField($params,'end_time'),function ($query)use ($params){
            $query->where('created_at','<=',strtotime($params['end_time'].' 23:59:59'));
        });


        return $query;
    }

    /**
     * @throws SysExceptions
     */
    public static function rechargeUsers(array $params = [])
    {
        checkForData(
            ['nums','pay_type'],
            ['请输入金额','请输入类型'],
            $params
        );
        $pParams = [
            'user_id'=>$params['user_id'],
            'nums'=>$params['nums'],
            'pay_type'=>$params['pay_type'],
            'order_code'=>makeOrderNo()
        ];
        if($params['pay_type'] == 2){
            if(!checkIsHasField($params,'img_url')){
                self::error('请上传凭证');
            }
            $pParams['img_url']=$params['img_url'];
        }
        if(self::builder_query()->create($pParams) === false){
            self::error('订单创建失败');
        }
        $info = UsersDao::builder_user_query(['user_id'=>$params['user_id']])->first()->toArray();

        $openid = UsersDao::builder_user_login_query([
            'user_login_id'=>$info['user_login_id'],
        ])->value('openid');
        return PayServices::pay([
            'name'=>'充值金额',
            'price'=>$params['nums'],
            'order_code'=>$pParams['order_code'],
            'openid'=>$openid,
            'notify_url'=>route('notice_recharge')
        ]);
    }

    public static function rechargeLists(array $params)
    {
        return self::builder_query($params)->get();
    }

    /**
     * @throws SysExceptions
     */
    public static function recOrder($out_trade_no)
    {
        $query = self::builder_query([
            'order_code'=>$out_trade_no,
            'status'=>0
        ]);
        if(!$query->exists()){
            self::error('订单不存在');
        }
        $info = $query->first()->toArray();
        DB::beginTransaction();
        try {
            BillsDao::moneyUpdate($info['user_id'],$info['nums'],'用户移动端充值');
            $query->update([
                'status'=>1
            ]);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error();
        }

    }

    public static function pageinage(array $all): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return self::builder_query(array_merge($all,[
            'pay_type'=>2
        ]))->orderByDesc('created_at')->paginate();
    }

    public static function info(array $all)
    {
        return self::builder_query($all)->orderByDesc('created_at')->first();
    }

    public static function recharge_audit(array $params)
    {
        checkForData(
            ['status'],
            ['请选择状态'],
            $params
        );
        $query = self::builder_query([
            'recharge_id'=>$params['recharge_id']
        ]);
        if(!$query->exists()){
            self::error('不存在');
        }
        $info = $query->first()->toArray();
        if($info['status'] != 0){
            self::error('订单状态不正确');
        }
        DB::beginTransaction();
        try {
            $query->update(self::filterFields($params,new RechargeModel()));
            if($params['status'] == 1){
                BillsDao::moneyUpdate($info['user_id'],$info['nums'],'线下充值');
            }
            DB::commit();
        }catch ( \Exception $exception){
            DB::rollBack();
            self::error();
        }

    }
}
